<template>
  <div class="container">
    <el-card>
      <h2>NSFW 图片检测</h2>

      <!-- 图片上传 -->
      <el-upload ref="upload" :auto-upload="false" list-type="picture" :limit="1" :on-change="handleFileChange"
        :on-remove="handleRemove">
        <el-button type="primary">选择图片</el-button>
      </el-upload>

      <!-- 触发分析按钮 -->
      <el-button type="success" @click="analyzeImage" :loading="loading">开始分析</el-button>

      <!-- 结果展示 -->
      <el-table v-if="results && results.length > 0" :data="results" style="margin-top: 20px">
        <el-table-column prop="label" label="类别" width="150"></el-table-column>
        <el-table-column prop="score" label="概率" width="100">
          <template #default="{ row }">
            <span :class="{ 'highlight': row.score === maxScore }">{{ row.score }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import { ref } from "vue";
import axios from "axios";
import { ElMessage } from "element-plus";

export default {
  setup() {
    const fileList = ref([]);
    const results = ref([]); // ✅ 确保 results 初始化为空数组
    const maxScore = ref(""); // 存储最高分
    const loading = ref(false);

    // 类别映射
    const categoryMap = {
      drawings: "drawings (漫画插图)",
      hentai: "hentai (变态)",
      neutral: "neutral (正常)",
      porn: "porn (色情)",
      sexy: "sexy (性感)"
    };

    // 处理文件选择
    const handleFileChange = (file) => {
      fileList.value = [file.raw]; // 只存一个文件
    };

    // 处理文件删除
    const handleRemove = () => {
      fileList.value = [];
      results.value = []; // ✅ 删除后清空结果
      maxScore.value = "";
    };

    // 发送请求进行图片分析
    const analyzeImage = async () => {
      if (fileList.value.length === 0) {
        ElMessage.warning("请选择一张图片");
        return;
      }

      loading.value = true;
      results.value = []; // ✅ 清空上一次的结果
      maxScore.value = "";

      const formData = new FormData();
      formData.append("file", fileList.value[0]); // 关键：参数名必须是 `file`

      try {
        const response = await axios.post("http://frp.huisonglin.top:2228/analyze/", formData, {
          headers: { "Content-Type": "multipart/form-data" },
        });

        console.log(response.data);
        const predictions = response.data.predictions;

        // 计算转换数据
        let formattedResults = Object.keys(predictions).map(key => ({
          label: categoryMap[key] || key, // 中文类别
          score: (predictions[key] * 100).toFixed(2) + "%" // 乘 100 变为百分比格式
        }));

        results.value = formattedResults;

        // 找到最高的分数
        maxScore.value = Math.max(...Object.values(predictions).map(v => (v * 100).toFixed(2))) + "%";

        ElMessage.success("识别完成！");
      } catch (error) {
        console.error(error);
        ElMessage.error("识别失败，请检查后端");
      } finally {
        loading.value = false;
      }
    };

    return {
      fileList,
      results,
      maxScore,
      loading,
      handleFileChange,
      handleRemove,
      analyzeImage,
    };
  },
};
</script>

<style>
/* 高亮最大值 */
.highlight {
  color: red;
  font-weight: bold;
}

.container {
  max-width: 600px;
  margin: 50px auto;
  padding: 20px;
}
</style>
